package com.primaryedu.ui.exercise;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.primaryedu.R;
import com.primaryedu.bean.CommonTwoBean;
import com.primaryedu.data.Config;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.dialog.PhotosDialog;
import com.primaryedu.picture.PicturePreviewActivity;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.utils.ImageUtil;
import com.primaryedu.utils.UploadUtil;
import com.primaryedu.utils.UploadUtil.OnUploadProcessListener;
import com.primaryedu.widget.ClearEditText;
import com.primaryedu.widget.MyGridView;

/**
 * 写评论窗体
 *
 * @author jun.wang
 * @description
 * @data 2016年12月19日
 */
public class CommentWriteActivity extends BaseActivity implements OnClickListener, OnUploadProcessListener {
    private TextView text_right;
    private ClearEditText edit;
    private MyGridView gridView;
    CommentPhotoAdapter adapter;
    List<CommonTwoBean> list;

    private PhotosDialog.Builder Builder;
    Dialog dialog;

    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    /*图片名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";

    private String imagePath = "";
    private File tempFile;
    private Bitmap bitmap;

    /**
     * 去上传文件
     */
    protected static final int TO_UPLOAD_FILE = 1;
    /**
     * 上传文件响应
     */
    protected static final int UPLOAD_FILE_DONE = 2; //
    /**
     * 选择文件
     */
    public static final int TO_SELECT_PHOTO = 3;
    /**
     * 上传初始化
     */
    private static final int UPLOAD_INIT_PROCESS = 4;
    /**
     * 上传中
     */
    private static final int UPLOAD_IN_PROCESS = 5;
    /***
     * 这里的这个URL是我服务器的javaEE环境URL
     */
    private static String requestURL = "http://www.nj12z.net/rest/comment/upload";

    private String picpath1 = "";
    private String picpath2 = "";
    private String picpath3 = "";
    LayoutInflater inflater;

    private String newId = "";
    private String type = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_comment_write);

        newId = getIntent().getStringExtra("newId");
        type = getIntent().getStringExtra("type");
        init();
    }

    private void init() {
        inflater = LayoutInflater.from(this);
        ((TextView) findViewById(R.id.title)).setText("发布评论");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.right).setVisibility(View.VISIBLE);
        text_right = (TextView) findViewById(R.id.text_right);
        text_right.setText("发布");
        text_right.setOnClickListener(this);
        text_right.setTextColor(getResources().getColor(R.color.main_button));
        gridView = (MyGridView) this.findViewById(R.id.gridView);
        edit = (ClearEditText) this.findViewById(R.id.edit);

        list = new ArrayList<>();
//		CommonTwoBean bean = new CommonTwoBean() ;
//		bean.setName("测试");
//		bean.setIcon("http://img1sw.baidu.com/soft/18/17521/2cd3f9fe459324e3fa4af25004b040d4.png");
//		list.add(bean) ;
//		
//		CommonTwoBean bean2 = new CommonTwoBean() ;
//		bean2.setName("测试2");
//		bean2.setIcon("http://img1sw.baidu.com/soft/18/17521/2cd3f9fe459324e3fa4af25004b040d4.png");
//		list.add(bean2) ;

        adapter = new CommentPhotoAdapter(this, list);
        gridView.setAdapter(adapter);
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_comment_write;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            case R.id.text_right:
                commitData();
                break;

            default:
                break;
        }
    }

    private static Mode mMode = Mode.NORMAL;

    private enum Mode {
        DEL, NORMAL
    }

    ;

    class CommentPhotoAdapter extends BaseAdapter {

        private Context context;
        LayoutInflater inflater;
        List<CommonTwoBean> list = new ArrayList<>();
//        LoadImage loadImage;
        protected RequestQueue requestQueue = null;
        private int currentPos = 0;

        public CommentPhotoAdapter(Context context, List<CommonTwoBean> list) {
            this.context = context;
            this.list = list;
//            loadImage = LoadImage.getInstance();
            inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            requestQueue = Volley.newRequestQueue(context);
        }

        @Override
        public int getCount() {
            return list.size() + 2;
        }

        @Override
        public Object getItem(int position) {
            if (position >= list.size())
                position = list.size() - 1;
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            //视图循环利用优化
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.item_comment_photo, null);
                holder.icon = (ImageView) convertView.findViewById(R.id.item_icon);
                holder.del = (ImageView) convertView.findViewById(R.id.item_del);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            //加号部分
            if (position == list.size()) {
                holder.icon.setImageResource(R.drawable.icon_jia);
                holder.icon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showPhoto();
                    }
                });
                holder.del.setVisibility(View.GONE);
            } else if (position == list.size() + 1) {//减号部分
                holder.icon.setImageResource(R.drawable.icon_jian);
                holder.icon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mMode == Mode.NORMAL) {
                            mMode = Mode.DEL;
                        } else {
                            mMode = Mode.NORMAL;
                        }
                        refreshUI();
                    }
                });
                holder.del.setVisibility(View.GONE);
            } else {//正常的头像展示部分
                final CommonTwoBean bean = list.get(position);
                holder.icon.setTag(Contants.course_api + bean.getIcon());
                Glide.with(context)
                        .load(Contants.course_api + bean.getIcon())
                        .placeholder(R.drawable.default_error)
                        .error(R.drawable.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(holder.icon);

//                loadImage.addTask(Contants.course_api + bean.getIcon(), holder.icon);
//                loadImage.doTask();

                holder.icon.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        mMode = Mode.DEL;
                        refreshUI();
                        return true;
                    }
                });

                if (mMode == Mode.NORMAL) {
                    holder.del.setVisibility(View.GONE);
                } else {
                    holder.del.setVisibility(View.VISIBLE);
                }

                holder.del.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        list.remove(position);
                        notifyDataSetChanged();
                    }
                });

                holder.icon.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (!TextUtils.isEmpty(Contants.course_api + bean.getIcon())) {
                            Intent intent = new Intent(context, PicturePreviewActivity.class);
                            intent.putExtra("url", Contants.course_api + bean.getIcon());
                            startActivity(intent);
                        }
                    }
                });
            }

            return convertView;
        }

        public void refreshUI() {
            notifyDataSetChanged();
        }

        private class ViewHolder {
            ImageView icon;
            ImageView del;
        }
    }

    ;

    private void showPhoto() {
        Builder = new PhotosDialog.Builder(CommentWriteActivity.this);
        dialog = Builder.create();
        View view = inflater.inflate(R.layout.dialog_photo, null);

        view.findViewById(R.id.image_take).setOnClickListener(this);
        view.findViewById(R.id.image_video).setOnClickListener(this);

        // 相册
        view.findViewById(R.id.image_video).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

                Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
                getImage.addCategory(Intent.CATEGORY_OPENABLE);
                getImage.setType("image/*");
                startActivityForResult(getImage, PHOTO_REQUEST_GALLERY);
            }
        });

        // 拍照
        view.findViewById(R.id.image_take).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                // 判断存储卡是否可以用，可用进行存储
                if (hasSdcard()) {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment
                                    .getExternalStorageDirectory(), PHOTO_FILE_NAME)));
                }

                startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
            }
        });

        dialog.addContentView(view, new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();       //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 1.0);    //宽度设置为屏幕的0.9
        p.height = (int) (d.getHeight() * 0.5);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.setCanceledOnTouchOutside(true);
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }

        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            if (hasSdcard()) {
                tempFile = new File(Environment.getExternalStorageDirectory(),
                        PHOTO_FILE_NAME);
                crop(Uri.fromFile(tempFile));

            } else {
                Toast.makeText(CommentWriteActivity.this, "未找到存储卡，无法存储照片！", 0)
                        .show();
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            try {
                bitmap = data.getParcelableExtra("data");
//				this.headImage.setImageBitmap(bitmap);
                // 删除临时文件
                ImageUtil.saveToSdcard(bitmap);
                imagePath = Config.SDPATH_HEAD + "temp_photo.jpg";

                // 替换服务器上面的头像
                toUploadFile();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 剪切图片
     *
     * @param uri
     * @function:
     * @author:Jerry
     * @date:2015-04-15
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private void toUploadFile() {
        String fileKey = "pic1";   // 服务器与客户端协调好的key值或叫name值

        System.out.println("fileKey==" + fileKey);
        System.out.println("fileKey=00=" + list.size());

        UploadUtil uploadUtil = UploadUtil.getInstance();
        uploadUtil.setOnUploadProcessListener(this); // 设置监听器监听上传状态

        System.out.println("temp_photo==" + Config.SDPATH_HEAD + "temp_photo.jpg");
        uploadUtil.uploadFile(Config.SDPATH_HEAD + "temp_photo.jpg", fileKey,
                requestURL, null);
    }

    @Override
    public void onUploadDone(int responseCode, String message) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_FILE_DONE;
        msg.arg1 = responseCode;
        msg.obj = message;
        handler.sendMessage(msg);
    }

    @Override
    public void onUploadProcess(int uploadSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_IN_PROCESS;
        msg.arg1 = uploadSize;
        handler.sendMessage(msg);
    }

    @Override
    public void initUpload(int fileSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_INIT_PROCESS;
        msg.arg1 = fileSize;
        handler.sendMessage(msg);
    }

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
//				setData() ;
                    break;

                case UPLOAD_FILE_DONE:
                    String jsonStr = msg.obj.toString();
                    System.out.println("json===" + jsonStr);

                    try {
                        JSONObject json = new JSONObject(jsonStr);
                        int result = json.getInt("result");
                        String reason = json.getString("reason");

                        if (result == 1) {
                            String data = json.getString("data");
                            JSONObject listObj = new JSONObject(data);
                            picpath1 = listObj.getString("picpath1");
                            String webServerUrl = listObj.getString("webServerUrl");

                            if (!TextUtils.isEmpty(picpath1)) {
                                CommonTwoBean bean = new CommonTwoBean();
//								  bean.setIcon(webServerUrl+picpath1);
                                bean.setIcon(picpath1);
                                list.add(bean);
                            }

                            if (null != list && list.size() != 0) {
                                adapter = new CommentPhotoAdapter(CommentWriteActivity.this, list);
                                gridView.setAdapter(adapter);
                            }
                        } else {
                            showToast(reason);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    private void commitData() {
        if (TextUtils.isEmpty(edit.getText().toString())) {
            showToast("请输入评论内容");
            return;
        }

        // 三个图片路径
        if (list.size() != 0) {

            if (list.size() == 1) {
                picpath1 = list.get(0).getIcon();
            } else if (list.size() == 2) {
                picpath1 = list.get(0).getIcon();
                picpath2 = list.get(1).getIcon();
            } else if (list.size() == 3) {
                picpath1 = list.get(0).getIcon();
                picpath2 = list.get(1).getIcon();
                picpath3 = list.get(2).getIcon();
            }
        }

        System.out.println("picpath1=1=" + picpath1);
        System.out.println("picpath=2=" + picpath2);
        System.out.println("picpath1=3=" + picpath3);

        requestData();
    }

    private void requestData() {
        showDialog();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.saveComment,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("saveComment=000=" + response);
                        closeDialog();
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            String reason = json.getString("reason");

                            if (result == 1) {
                                showToast(reason);
                                finish();
                            } else {
                                showToast(reason);
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                closeDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("userid", GlobalData.getUserId(CommentWriteActivity.this));
                map.put("objectid", newId);
                map.put("content", edit.getText().toString());
                map.put("type", type);
                map.put("pic1", picpath1);
                map.put("pic2", picpath2);
                map.put("pic3", picpath3);

                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

}
